package com.jemmyee.pizza.web.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.jemmyee.core.dao.Page;
import com.jemmyee.core.utils.EncryptUtils;
import com.jemmyee.pizza.entity.Excerpt;
import com.jemmyee.pizza.entity.LogSys;
import com.jemmyee.pizza.entity.Person;
import com.jemmyee.pizza.entity.Role;
import com.jemmyee.pizza.entity.User;
import com.jemmyee.pizza.service.IExcerptService;
import com.jemmyee.pizza.service.ILogSysService;
import com.jemmyee.pizza.service.IPersonService;
import com.jemmyee.pizza.service.IRoleService;
import com.jemmyee.pizza.service.IUserService;
import com.jemmyee.pizza.web.Constants;
import com.jemmyee.pizza.web.bean.ExcerptBean;
import com.jemmyee.pizza.web.bean.PrivilegeBean;
import com.jemmyee.pizza.web.utils.PrivilegeUtils;

/**
 * @Description:后台主框架的控制器
 * @author:jemmyee@gmail.com
 * @date:2010-10-20
 * @version:v1.0
 */
@Controller
@RequestMapping("/main")
public class MainController {

	private static Log log = LogFactory.getLog(MainController.class);

	@Autowired
	private IUserService<User> userService;
	@Autowired
	private IRoleService<Role> roleService;
	@Autowired
	private ILogSysService<LogSys> logSysService;
	@Autowired
	private IExcerptService excerptService;
	@Autowired
	private IPersonService<Person> personService;

	/**
	 * @Description:系统登录页
	 * @author:jemmyee@gmail.com
	 * @date:2010-10-20
	 */
	@RequestMapping("/index")
	public ModelAndView index() {
		ModelAndView mv = new ModelAndView();
		return mv;
	}

	/**
	 * @Description:登录动作
	 * @author:jemmyee@gmail.com
	 * @date:2010-10-20
	 */
	@RequestMapping("/login/{type}")
	public ModelAndView login(@ModelAttribute("user") User user,
			@RequestParam String vcode, @PathVariable Integer type,
			HttpServletRequest request) {

		LogSys logSys = new LogSys();
		logSys.setLtime(new Date());
		logSys.setType(1);

		ModelAndView mv = new ModelAndView();
		// 判断验证码是否正确
		String validateCode = request.getSession().getAttribute("validateCode")
				.toString();
		if (!vcode.equalsIgnoreCase(validateCode)) {
			mv.addObject("loginError", "验证码不正确");
			mv.addObject("name", user.getName());
			mv.addObject("password", user.getPassword());
			mv.setViewName("/main/index");
			return mv;
		}
		if (type != null && type == 1) {
			DetachedCriteria dc = DetachedCriteria.forClass(Person.class);
			dc.add(Restrictions.eq("personNumber", user.getName()));
			dc.add(Restrictions.eq("passWord", user.getPassword()));
			List<Person> personList = personService.findByCriteria(dc);
			if (personList != null && personList.size() > 0) {
				dc = DetachedCriteria.forClass(Excerpt.class);
				dc.add(Restrictions.like("personNumber", user.getName(),
						MatchMode.ANYWHERE));
				// dc.addOrder(Order.desc("excerptTime"));
				Page page = excerptService.findPageByCriteria(dc,
						Constants.DEFAULT_PAGESIZE, 0, "excerptTime");

				ExcerptBean excerptBean = new ExcerptBean();
				excerptBean.setNumber(user.getName());
				mv.addObject("excerptBean", excerptBean);
				mv.addObject("page", page);
				mv.setViewName("/admin/excerpt/list_for_person");
			} else {
				mv.addObject("loginError", "登录失败,用户名或密码错误");
				mv.setViewName("/main/index");
			}
		} else {
			List<User> users = userService.findByProperty("name", user
					.getName());
			if (users != null && users.size() < 1)// 账户不存在
			{
				mv.addObject("loginError", "登录失败,用户名不存在");
				mv.setViewName("/main/index");
				// 记录日志
				logSys.setLdesc("用户登录    登录结果:失败    用户名:" + user.getName()
						+ " 密码:" + user.getPassword());
			} else {
				User temp = users.get(0);
				if (temp.getPassword().equals(
						EncryptUtils.getMD5String(user.getPassword())))// 验证通过
				{
					request.getSession().setAttribute(Constants.ONLINE_ADMIN,
							user.getName());
					request.getSession().setAttribute(
							Constants.ONLINE_USERNAME, temp.getRealname());
					// 进入一个中间301重定向页面，避免浏览器F5刷新登录
					mv.setViewName("/main/redirect");
					// 记录最后登录时间
					temp.setLastloginTime(new Date());
					userService.save(temp);
					// 记录权限
					PrivilegeBean pb = new PrivilegeBean();
					String roles = temp.getRoleIDS();
					String rights = "";
					if (!roles.equals("0")) {
						for (String id : roles.split("_")) {
							if (!id.equals("")) {
								int iid = Integer.parseInt(id);
								Role role = roleService.findById(iid);
								// if(!role.getRights().equals("0"))
								if (!"".equals(role.getRights())) {
									rights = rights + role.getRights();
								}

							}
						}
					}
					pb = PrivilegeUtils.initPrivileges(rights);
					request.getSession().setAttribute("pv", pb);
					// 权限设置结束

					logSys.setLdesc("用户登录    登录结果:成功    用户名:" + user.getName()
							+ " 密码:" + user.getPassword());
				} else// 验证不通过,密码不正确
				{
					mv.addObject("loginError", "密码不正确");
					mv.addObject("name", user.getName());
					mv.setViewName("/main/index");

					logSys.setLdesc("用户登录    登录结果:失败    用户名:" + user.getName()
							+ " 密码:" + user.getPassword());
				}
			}
			try {
				logSysService.save(logSys);
			} catch (Exception e) {
				log.error("errr:" + e.getMessage());
			}
		}

		return mv;
	}

	/**
	 * @Description:退出
	 * @author:jemmyee@gmail.com
	 * @date:2010-10-20
	 */
	@RequestMapping("/exit")
	public String exit(HttpServletRequest request, HttpServletResponse response) {
		request.getSession().removeAttribute(Constants.ONLINE_ADMIN);
		// 回到根目录，也就是首页
		return "redirect:/";
	}

	/**
	 * @Description:主框架
	 * @author:jemmyee@gmail.com
	 * @date:2010-10-20
	 */
	@RequestMapping("/frame")
	public ModelAndView frame() {
		ModelAndView mv = new ModelAndView();
		return mv;
	}

	/**
	 * @Description:框架头部
	 * @author:jemmyee@gmail.com
	 * @date:2010-10-20
	 */
	@RequestMapping("/header")
	public ModelAndView top() {
		ModelAndView mv = new ModelAndView();
		return mv;
	}

	/**
	 * @Description:框架底部
	 * @author:jemmyee@gmail.com
	 * @date:2010-10-20
	 */
	@RequestMapping("/footer")
	public ModelAndView footer() {
		ModelAndView mv = new ModelAndView();
		return mv;
	}

	/**
	 * @Description:左侧菜单
	 * @author:jemmyee@gmail.com
	 * @date:2010-10-20
	 */
	@RequestMapping("/left")
	public ModelAndView menu_common() {
		ModelAndView mv = new ModelAndView();
		return mv;
	}

	/**
	 * @Description:右侧欢迎页面
	 * @author:jemmyee@gmail.com
	 * @date:2010-10-20
	 */
	@RequestMapping("/right")
	public ModelAndView right() {
		ModelAndView mv = new ModelAndView();
		return mv;
	}

	/**
	 * @Description:中间伸缩页面
	 * @author:jemmyee@gmail.com
	 * @date:2010-10-20
	 */
	@RequestMapping("/split")
	public ModelAndView split() {
		ModelAndView mv = new ModelAndView();
		return mv;
	}

	/**
	 * @Description:系统设置界面
	 * @author:jemmyee@gmail.com
	 * @date:2010-11-15
	 */
	@RequestMapping("/toset")
	public ModelAndView toset() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/admin/sys/set");
		return mv;
	}

	@RequestMapping("/bzdj")
	public ModelAndView bzdj() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/admin/demo/bzdj");
		return mv;
	}

}
